<template>
  <div>
    <div style="text-align: end; margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="handleBindPrams">
          <template #icon>
            <icon-link />
          </template>
          绑定参数
        </a-button>
      </a-space>
    </div>
    <a-spin :loading="data.loading">
      <a-table :data="data.tableData" :columns="data.columns" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #status="{ record }">
          <template v-if="record.state === 1">
            <a-tag color="green">已启用</a-tag>
          </template>
          <template v-else>
            <a-tag color="red">已停用</a-tag>
          </template>
        </template>
        <template #action="{ record }">
          <a-space>
            <template v-if="record.state === 1">
              <a-button type="text" size="small" status="warning" @click="handleRunAnalyse(record, false, getList)">
                <template #icon>
                  <icon-stop />
                </template>
                停用
              </a-button>
            </template>
            <template v-else>
              <a-button type="text" size="small" status="success" @click="handleRunAnalyse(record, true, getList)">
                <template #icon>
                  <icon-play-arrow />
                </template>
                启用
              </a-button>
            </template>

            <a-button type="text" size="small" @click="handleBindParamsUpdata(record)"> 修改 </a-button>
            <a-button type="text" size="small" status="danger" @click="handleBindParamsDelete(record)"> 删除 </a-button>
          </a-space>
        </template>
      </a-table>
      <a-pagination
        :total="data.pagination.total"
        :current="data.pagination.pageStart"
        :page-size="data.pagination.pageLength"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      ></a-pagination>
    </a-spin>
    <a-modal
      v-if="data.bindVisible"
      title="绑定参数"
      v-model:visible="data.bindVisible"
      width="700px"
      @before-ok="handleBindParamsOk"
    >
      <a-form :model="data.form" ref="formRef">
        <a-form-item label="模板" field="tempId" :rules="[{ required: true, message: '请选择模板' }]">
          <!-- <a-select v-model="data.form.templateName" placeholder="请选择">
            <a-option
              v-for="item in data.thresholdList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select> -->
          <div class="flex flex-col">
            <a-input-search
              style="border-radius: 15px; margin-bottom: 5px; width: 200px"
              placeholder="输入可筛选模板名称"
              size="small"
              v-model="tableSearch"
            />
            <a-table
              style="width: 100%"
              size="small"
              :scroll="{
                maxHeight: '300px'
              }"
              :columns="columns"
              row-key="id"
              :data="data.thresholdList.filter((item) => item.name.indexOf(tableSearch) > -1)"
              :row-selection="rowSelection"
              :selected-keys="data.selectedKeys"
              @select="handleSelect"
              :pagination="false"
              align="center"
            >
            </a-table>
          </div>
        </a-form-item>
        <a-form-item label="参数">
          <a-select value-key="paramId" allow-search allow-clear placeholder="请选择" v-model="data.form.paramsInfo">
            <a-option v-for="item in paramsList" :key="item.id" :value="item" :label="item.paramName"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="监测次数">
          <!-- <a-input v-model="data.form.times" placeholder="请输入"></a-input> -->
          <a-select v-model="data.form.times" placeholder="请选择">
            <a-option :value="1">1</a-option>
            <a-option :value="2">2</a-option>
            <a-option :value="3">3</a-option>
            <a-option :value="4">4</a-option>
            <a-option :value="5">5</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="告警级别">
          <a-select v-model="data.form.alarmLevel" placeholder="请选择">
            <a-option :value="1">1</a-option>
            <a-option :value="2">2</a-option>
            <a-option :value="3">3</a-option>
            <a-option :value="4">4</a-option>
            <a-option :value="5">5</a-option>
            <a-option :value="6">6</a-option>
            <a-option :value="7">7</a-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { apiAnalysis } from '@/api/analysis'
import { handleRunAnalyse } from '@/views/algorithmBinding/bind/api'
const tableSearch = ref('')
const props = defineProps({
  deviceId: {
    type: String,
    default: ''
  },
  paramsList: {
    type: Array,
    default: () => []
  },
  currentSatellite: {
    type: Object,
    default: () => {}
  }
})

const rowSelection = {
  type: 'radio'
}

const columns = [
  {
    title: '模板名称',
    dataIndex: 'name'
  },
  {
    title: '监测帧数',
    dataIndex: 'monitorNum'
  },
  {
    title: '监测值',
    dataIndex: 'value'
  },
  {
    title: '备注',
    dataIndex: 'notes'
  }
]

const data = reactive({
  loading: false,
  tableData: [],
  satelitesList: [],
  columns: [
    {
      title: '序号',
      slotName: 'index',
      width: 60,
      customRender: ({ index }) => {
        return index + 1 + (data.pagination.pageStart - 1) * data.pagination.pageLength
      }
    },
    {
      title: '模板名称',
      dataIndex: 'tempName'
    },
    {
      title: '告警级别',
      dataIndex: 'alarmLevel'
    },
    {
      title: '监测帧数',
      dataIndex: 'times'
    },
    {
      title: '运行状态',
      dataIndex: 'state',
      slotName: 'status'
    },
    // { title: "级别", dataIndex: "alarmLevel" },
    // { title: "创建时间", dataIndex: "createDate" },
    { title: '操作', slotName: 'action', width: 150 }
  ],
  satelliteId: null,
  selectedKeys: [],
  pagination: {
    total: 0,
    pageStart: 1,
    pageLength: 10
  },
  bindVisible: false,
  form: {
    timeList: [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  },
  thresholdList: [],
  templateFlag: 0
})
const formRef = ref(null)

const handleBindParamsUpdata = (record) => {
  data.bindVisible = true
  apiAnalysis.getConstantMonitorBindingDetail(record.id).then((res) => {
    if (res.code === 200) {
      data.form = res.data
      data.selectedKeys = [res.data.tempId]
      data.form.tempId = res.data.tempId
      data.form.tempName = res.data.tempName
      data.form.paramsInfo = {
        ...res.data
      }
    }
  })
}

const handleBindParamsDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      apiAnalysis.deleteConstantMonitorBinding(record.id).then((res) => {
        if (res.code === 200) {
          Message.success('删除成功')
          getList()
        }
      })
    }
  })
}

const handleBindPrams = () => {
  data.bindVisible = true
  data.selectedKeys = []
  data.form = {}
}

const addTime = () => {
  data.form.timeList.push({
    state: 1,
    time: [],
    startTime: '',
    endTime: ''
  })
}

const deleteTime = (index) => {
  data.form.timeList.splice(index, 1)
}

const handleSelect = (rowKeys, rowKey, record) => {
  console.log(rowKeys, 'rowKeys')
  console.log(rowKey, 'rowKey')
  console.log(record, 'record')
  data.selectedKeys = rowKeys
  data.form.tempId = rowKey
  data.form.tempName = record.name
  // if (record.conditionSet === 1) {
  //   data.templateFlag = 1;
  // } else if (record.conditionSet === 2) {
  //   data.templateFlag = 2;
  // } else {
  //   data.templateFlag = 3;
  // }
}

const handleBindParamsOk = (done) => {
  formRef.value.validate().then((col) => {
    console.log(data.form, 'data.form')
    const {
      satCode,
      satId,
      satName,
      subsystemId,
      subsystemName,
      deviceCode,
      deviceId,
      deviceName,
      paramCode,
      paramId,
      paramName
    } = data.form.paramsInfo
    data.form = {
      ...data.form,
      satCode,
      satId,
      satName,
      subsystemId,
      subsystemName,
      deviceCode,
      deviceId,
      deviceName,
      paramCode,
      paramId,
      paramName
    }
    // if (data.templateFlag === 3) {
    //   data.form.timeList = data.form.timeList.map((item) => {
    //     return {
    //       ...item,
    //       startTime: item.time[0],
    //       endTime: item.time[1],
    //     };
    //   });
    // } else {
    //   delete data.form.timeList;
    // }
    if (!col) {
      const api = data.form.id ? apiAnalysis.updateConstantMonitorBinding : apiAnalysis.addConstantMonitorBinding

      api(data.form).then((res) => {
        if (res.code === 200) {
          Message.success('绑定成功')
          data.bindVisible = false
          getList()
        } else {
          Message.error('绑定失败')
        }
      })
      done(true)
    } else {
      done(false)
    }
  })
}

const getThresholdList = () => {
  apiAnalysis
    .getPageList({
      pageNum: 1,
      pageSize: 100
    })
    .then((res) => {
      if (res.code === 200) {
        data.thresholdList = res.data.list
      }
    })
}

const handlePageChange = (page) => {
  data.pagination.pageStart = page
  getList()
}

const handlePageSizeChange = (size) => {
  data.pagination.pageLength = size
  getList()
}

watch(
  () => props.deviceId,
  () => {
    getList()
  }
)

const getList = () => {
  console.log(props.deviceId, 'props.deviceId')
  data.loading = true
  apiAnalysis
    .getConstantMonitorBindingList(Object.assign(data.pagination, { deviceId: props.deviceId }))
    .then((res) => {
      if (res.code === 200) {
        data.loading = false
        data.tableData = res.data.list
        data.pagination.total = +res.data.total
      } else {
        data.loading = false
      }
    })
    .finally(() => {
      data.loading = false
    })
}

onMounted(() => {
  getThresholdList()
  getList()
})
</script>

<style scoped>
:deep(.arco-btn-size-small) {
  padding: 5px;
}
</style>
